/*

    file:   sound.c
    desc:   Simple audio square wave sequencer.

    author: Jaromir Dvorak (md@unicode.cz)

    This file is part of the AVGA platform.
    http://avga.prometheus4.com/


    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
 
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
  
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
*/

#include <avr/io.h>
#include <avr/pgmspace.h>
#include "sound.h"


#ifdef SOUND_ENABLE
#ifdef SOUND_ENABLE_SYNTHESIZER

void inline sound_line_handle()
{
	static unsigned int ch1pos, ch2pos, ch3pos, ch4pos;
	
	signed int output = 0;
	
	output += ((signed int)pgm_read_byte(&bank1[s1pos>>8]) * ch1vol) >> 8;
	s1pos += s1freq;
	output += ((signed int)pgm_read_byte(&bank2[s2pos>>8]) * ch2vol) >> 8;
	s2pos += s2freq;
	output += ((signed int)pgm_read_byte(&bank3[s3pos>>8]) * ch3vol) >> 8;
	s3pos += s3freq;
	output += ((signed int)pgm_read_byte(&bank4[s4pos>>8]) * ch4vol) >> 8;
	s4pos += s4freq;

	output >>= 3;
	OCR0A = output + 128;

}

#else

unsigned char  sound_timer = 0;
PGM_P sound_stream;


void sound_init()
{
	__sound_init_timer();
	__sound_stop_timer();
	SOUND_TIMER_DDR |= 1 << SOUND_TIMER_DDR_PIN;
}

void sound_play(PGM_P stream)
{
	sound_stream = stream;
	sound_timer = 1;
}


void sound_stop()
{
	sound_timer = 0;
	__sound_stop_timer();
}


void inline sound_frame_handle() //called by the video generator once a frame.
{
	if(sound_timer && !--sound_timer)
	{
		register unsigned char len = pgm_read_byte(sound_stream++); //len
		if(!len) 
		{  
			__sound_stop_timer();
			return; 
		
		}
		sound_timer = len;

		register unsigned char p = pgm_read_byte(sound_stream++); //freq
		__sound_set_timer(p);
	}
}

#endif
#endif





